/**
 * @param {string} uploadUrl url
 * @param {Array<string>} externalClasses 自定义样式
 */

const app = getApp();
Component({
  externalClasses: [
    'upload-item__container-class', 
    'upload-item__content-class', 
    'upload-item__picture-class', 
    'upload-item__del-btn-class',
    'icon', 'icon-jia',
  ],
  properties: {
    count: { // 控制文件数量
      type: Number,
      value: 1,
    },
    fileType: { // image, audio, video
      type: String,
      value: 'image',
    },
    fileName: {
      type: String,
      value: 'files',
    },
    fileArray: {
      type: Array,
      value: [],
    },
    uploadUrl: {
      type: String,
      value: 'utility/file/upload',
    },
    formData: {
      type: Object,
      value: {},
    },
    sizeType: {
      type: Array,
      value: ['original', 'compressed'],
    },
    sourceType: {
      type: Array,
      value: ['album', 'camera'],
    },
    compressed: {
      type: Boolean,
      value: true,
    },
    maxDuration: {
      type: Number,
      value: 60,
    },
    camera: {
      type: String,
      value: 'back',
    },
  },
  data: {
    attachment_url: app.siteInfo.attachment_url, // 图片资源路径前缀
  },
  methods: {

    _isJSON(str) {
      if (typeof str === 'string') {
        try {
          let obj = JSON.parse(str);
          if (typeof obj === 'object' && obj) {
            return true;
          } else {
            return false;
          }
        } catch (e) {
          return false;
        }
      }
    },

    // 图片上传 代码块
    previewImg(e) {
      let url = this.data.attachment_url + e.currentTarget.dataset.src;
      wx.previewImage({
        urls: [url],
      });
    },

    uploadPic() {
      let { count, fileArray, formData, sizeType, sourceType } = this.properties;
      count = count - fileArray.length;
      wx.chooseImage({
        count,
        sizeType,
        sourceType,
        success: (res) => {
          let tempFilePaths = res.tempFilePaths;
          wx.showLoading({ title: '上传中', mask: true });
          for (let i = 0; i < tempFilePaths.length; i++) {
            this.uploadFiles(fileArray, tempFilePaths[i], i, tempFilePaths.length, formData);
          }
        },
      });
    },

    uploadFiles(fileArray, filepath, index, num, formData) {
      let { fileType, fileName, uploadUrl } = this.properties;
      let surl = `${app.util.url(uploadUrl)}type=${fileType}`;
      
      const uploadTask = wx.uploadFile({
        url: surl,
        filePath: filepath,
        name: 'file',
        formData,
        success: (res) => {
          if (this._isJSON(res.data)) {
            const data = JSON.parse(res.data);
            if (data.error && Number(data.error.code) === 1) {
              wx.showModal({ title: '系统提示', content: data.error.message, showCancel: false });
              wx.hideLoading();
            } else {
              fileArray.push(data.url);
              this.setData({ fileArray });
              this.triggerEvent('uploadEvent', { [fileName]: fileArray }, { bubbles: false, composed: false, capturePhase: false });
              if (Number(index) === num - 1) {
                wx.hideLoading();
              }
            }
          } else {
            wx.showToast({ title: '上传图片格式有误', icon: 'none' });
          }
        },
        fail: (err) => {
          wx.showModal({ title: '系统提示', content: err.data.message, showCancel: false });
        },
      });
      
      uploadTask.onProgressUpdate((res) => {
      });
    },

    delPic(e) {
      let { index } = e.currentTarget.dataset;
      let { fileName, fileArray } = this.properties;
      wx.showModal({
        title: '提示信息',
        content: '确定删除吗？',
        success: res => {
          if (res.confirm) {
            fileArray.splice(index, 1);
            this.setData({ fileArray });
            this.triggerEvent(
              'uploadEvent', 
              {[fileName]: fileArray, fileName }, 
              { bubbles: false, composed: false, capturePhase: false }
            );
          } else if (res.cancel) {
          }
        },
      });
    },
  },
  
});
